package com.ship.edge.task;

import com.ship.edge.config.SystemConfig;
import com.ship.edge.utils.DirFileUtil;
import com.ship.edge.utils.MinioTemplate;
import com.ship.edge.utils.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@Component
public class ScheduledService {

    @Resource
    MinioTemplate minioTemplate;

    @Resource
    ZipUtil zipUtil;

    @Resource
    DirFileUtil dirFileUtil;


    @Scheduled(cron = "*/10 * * * * *")
    public void uploadKsbgCsvToMinIO() {
        OutputStream outputStream = null;
        try{
            log.info("=====>>>>>uploadKsbgCsvToMinIO  {}",System.currentTimeMillis());
            // 获取当前时间的前一个小时，1小时上传一次
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, (calendar.get(Calendar.HOUR_OF_DAY) - 1));
            String filePath = dirFileUtil.getFileDatePath(calendar, null, "yyyyMMdd", "yyyyMMddHH");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHH");
            // 将日期对象格式化为字符串
            String formattedDate = sdf1.format(calendar.getTime());
            //要压缩的文件路径
            File dir = new File(filePath);
            if(dir.exists()){
                //压缩后zip包文件路径
                String fileName = formattedDate + ".zip";
                String zipFilePath = filePath + fileName;
                File dest = new File(zipFilePath);
                outputStream = new FileOutputStream(dest);
                zipUtil.dirToZip(dir, outputStream, "csv");
                MultipartFile multipartFile = getMultipartFile(dest);
                String minioPath = dirFileUtil.minioPath("ksbg", fileName);
                minioTemplate.putObject(minioPath, multipartFile);
                log.info("================uploadKsbgCsvToMinIO {}成功======================", minioPath);
            }
        }catch (Exception ex){
            log.error("上传csv压缩文件失败--> {}", ex.getMessage());
        }finally {
            try{
                if(outputStream != null){
                    outputStream.close();
                }
            }catch (Exception ex){
                log.error("关闭zip压缩文件流失败--> {}", ex.getMessage());
            }
        }
    }

    @Scheduled(cron = "*/20 * * * * *")
    public void deleteLocalFile(){
        try{
            log.info("=====>>>>>deleteLocalFile  {}",System.currentTimeMillis());
            // 获取前15天的日期
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_MONTH, -15);
            String filePath = dirFileUtil.getFileDatePath(cal, null, "yyyyMMdd", null);
            File directory = new File(filePath);
            if(directory.exists()){
                FileUtils.deleteDirectory(directory);
                log.info("================定时任务删除{}目录下历史文件==========================", filePath);
            }
        }catch (Exception ex){
            log.error("定时清理历史文件失败--> {}", ex.getMessage());
        }
    }


    private static MultipartFile getMultipartFile(File file) {
        //如果传输有点问题可能传输的类型有点不同,可以试下更改为MediaType.TEXT_PLAIN_VALUE
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }
        return new CommonsMultipartFile(item);
    }

}
